package com.freewater.library.lending.book.application;

import com.freewater.library.lending.book.model.BookInstance;
import com.freewater.library.lending.book.model.BookInstanceRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class ReserveOverdueCheckTimerTask {

    private final BookInstanceRepository bookInstanceRepository;
    private final BookInstanceCommandService bookInstanceCommandService;

    @Scheduled(fixedRate = 8 * 1000, initialDelay = 10 * 1000)
    public void run() {
        List<BookInstance> reservingBooks = this.bookInstanceRepository.findReservingBooks();
        LocalDateTime nowTime = LocalDateTime.now();
        for (BookInstance reservingBook : reservingBooks) {
            this.bookInstanceCommandService.reserveOverdue(reservingBook, nowTime);
        }
        log.info("ReserveOverdueCheckTimerTask completed, checked {} books",
                reservingBooks.size());
    }
}
